/*
 *
 * Copyright (c) 2011 by Steve Devore
 *                       http://bookscanwizard.sourceforge.net
 *
 * This file is part of the Book Scan Wizard.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 */

package net.sourceforge.bookscanwizard.op;

import java.io.File;
import java.io.IOException;
import net.sourceforge.bookscanwizard.util.JpegMetaData;
import net.sourceforge.bookscanwizard.Operation;
import net.sourceforge.bookscanwizard.PageSet;

/**
 * This examines the focal from the jpeg exif metadata, and uses that
 * information to estimate the source DPI of the image.  This method assumes
 * that the distance to page remains the same, and the FocalLength accurately
 * represents the relative zoom level.
 */
public class EstimateDPI extends Operation {
    private static double x0;
    private static double y0;
    private static double x1;
    private static double y1;


    @Override
    public PageSet setup(PageSet pageSet) {
        double[] p = getArgs();
        x0 = p[0];
        y0 = p[1];
        x1 = p[2];
        y1 = p[3];
        return pageSet;
    }

    public static double calculateDPI(double x) {
        // interpolate result
        return ((x - x0) * y1 + (x1 - x) * y0) / (x1 - x0);
    }

    /**
     * Estimates the DPI of a file by examining the focal length
     *
     * @param file the file to estimate
     * @return the estimate dpi
     */
    public static double calculateDPI(File file) throws IOException {
        JpegMetaData metaData = new JpegMetaData(file);
        String fl = metaData.getValue("FocalLength");
        int pos = fl.indexOf("/");
        double focalLength;
        if (pos < 0) {
            focalLength = Double.parseDouble(fl);
        } else {
            focalLength = Double.parseDouble(fl.substring(0, pos)) /
                          Double.parseDouble(fl.substring(pos + 1));
        }
        return calculateDPI(focalLength);
    }
}
